﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LGPeWJNM.BaseClasses
{
    public class TriangleMatrix<U, T>
        where T : struct
        where U : struct, IEquatable<U>, IComparable<U>
    {
        private Dictionary<U, Dictionary<U, T>> dic { get; set; }
        public TriangleMatrix()
        {
            dic = new Dictionary<U, Dictionary<U, T>>();
        }
        public T this[U i, U j]
        {
            get
            {
                if (i.Equals(j))
                    throw new IndexOutOfRangeException("In a triangle matrix there is no diagonal elements, where i==j.");

                U min, max;
                if (i.CompareTo(j) < 0)
                {
                    min = i;
                    max = j;
                }
                else
                {
                    min = j;
                    max = i;
                }
                try
                {
                    return dic[min][max];
                }
                catch (Exception)
                {
                    return new Dictionary<U, T>()[max];
                }
            }
            set
            {
                if (i.Equals(j))
                    throw new IndexOutOfRangeException("In a triangle matrix there is no diagonal elements, where i==j.");

                var m = new U[] { i, j };
                if (!dic.ContainsKey(m.Min()))
                    dic[m.Min()] = new Dictionary<U, T>();
                dic[m.Min()][m.Max()] = value;
            }
        }
    }

}
